import React, {useEffect, useRef, useState} from 'react';
import {
    Button,
    message,
    Card,
    Form,
    Image,
    Input,
    Modal,
    Select,
    Space,
    Table,
    Tooltip,
    Steps,
    theme, Upload
} from 'antd';
import {
    reqDeleteArticleById,
    reqDeleteArticleList,
    reqGetArticleList,
    reqGetArticleSort, reqUpdateArticle
} from "../../../../api/backStage/backStageApi";
import {DeleteFilled, EditOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import {debounce} from "lodash";
import moment from "moment";
import MyQuill from "../../../../component/myQuill";
import axios from "axios";

const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const formItemLayout = {
    labelCol: {
        xs: {
            span: 8,
        },
        sm: {
            span: 8,
            offset: 1
        },
    },
    wrapperCol: {
        xs: {
            span: 6,
        },
        sm: {
            span: 6,
            offset: 0
        },
    },
};

const ArticleList = () => {

    const {Search} = Input
    //选择器的分类
    const [sortData, setSortData] = useState([]);
    //文章数据
    const [articleListData, setArticleListData] = useState([]);
    //点击选择框获取行信息
    const [articleSelectedRows, setArticleSelectedRows] = useState([])
    const [articleSelectedRowKeys, setArticleSelectedRowKeys] = useState([])
    //设置文章id
    const [articleId, setArticleId] = useState(null)
    //删除modal的控制
    const [open, setOpen] = useState(false);
    //确认按钮的异步
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [modalText, setModalText] = useState('删除之后不可恢复!')
    //修改按钮
    const [editArticle, setEditArticle] = useState(false)

    //修改封面时候的loading
    const [editCoverLoading, setEditCoverLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState()

    //步骤条
    const [current, setCurrent] = useState(0);

    //传递一个文章内容给子组件
    const [content, setContent] = useState('')
    const contentChange = (content) => {
        setContent(content)
    }

    //表单
    const [form] = Form.useForm()
    //表单数据
    const searchFormRef = useRef()

    useEffect(() => {
        //获取分类数据
        const getSortData = async () => {
            const result = await reqGetArticleSort()
            setSortData(result.data)
        }
        getSortData()
    }, [])

    useEffect(() => {
        //获取文章列表数据
        getArticleListData()
    }, [])

    useEffect(() => {
        if (editArticle) {
            form.setFieldValue({
                cover: imageUrl
            })
        }
    }, [imageUrl])
    const getArticleListData = async () => {
        const result = await reqGetArticleList()
        console.log(result)
        setArticleListData(result.data)
    }


    const next = () => {
        setCurrent(current + 1);
    };
    const prev = () => {
        setCurrent(current - 1);
    };

    const uploadButton = (
        <div>
            {editCoverLoading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8}}>
                Upload
            </div>
        </div>
    );

    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/admin/article-list/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            const error = new Error("Some error");
            onError(err);
        }
    }

    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }


    const uploadHandleChange = (info) => {
        if (info.file.status === 'uploading') {
            setEditCoverLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (url) => {
                setEditCoverLoading(false);
                setImageUrl([url]);
            });
        }
    };


    //点击修改按钮
    const updateArticle = (record) => {
        setContent(record.content)
        setEditArticle(true)
        setCurrent(0)
        setImageUrl([record.cover])
        setArticleId(record.id)
        //异步的
        if (form) {
            form.setFieldsValue({
                ...record,
                cover: imageUrl,
            })
        }
    }
    //修改文章成功的方法
    const updateOk = async () => {
        try {
            const articleInfo = {
                ...form.getFieldValue(),
                content,
            }
            await reqUpdateArticle({article_id: articleId, articleInfo})
        } catch (err) {
            message.error("修改文章失败")
        } finally {
            setEditArticle(false)
            message.success('修改文章成功!')
            getArticleListData()
        }
    }
    const steps = [
        {
            title: '编写基础信息',
            content: (
                <Form
                    form={form}
                    {...formItemLayout}
                    initialValues={{remember: true}}
                    style={{marginTop: 80}}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{required: true, message: "请输入标题!"}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="作者名字"
                        name="author_name"
                        rules={[{required: true, message: "请输入名字!"}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="分类"
                        name="sort"
                        rules={[{required: true, message: "请选择分类!"}]}
                    >
                        <Select
                            placeholder="选择文章类别"
                            options={sortData.map(item => ({value: item.sort, label: item.sort}))}
                        />
                    </Form.Item>

                    <Form.Item
                        label="文章简介"
                        name="describe"
                        rules={[{required: true, message: "请填写文章简介!"}]}
                    >
                        <Input.TextArea
                            style={{height: 150}}
                            size="large" showCount maxLength={300}/>
                    </Form.Item>

                    <Form.Item
                        label="文章封面"
                        name="cover"
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                        rules={[{required: true, message: "请选择文章封面!"}]}
                    >
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            showUploadList={false}
                            // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            beforeUpload={beforeUpload}
                            onChange={uploadHandleChange}
                            customRequest={customRequest}
                            maxCount={1}
                        >
                            {imageUrl ? (
                                <img
                                    alt="文章封面"
                                    src={imageUrl}
                                    style={{width: 100}}/>
                            ) : (
                                uploadButton
                            )}
                        </Upload>
                    </Form.Item>
                </Form>
            )
        },
        {
            title: '编写内容',
            content: (
                <div style={{marginTop: 30, display: 'flex', justifyContent: 'center'}}>
                    <MyQuill
                        width={1200}
                        height={500}
                        placeholder="请输入文章内容"
                        content={content}
                        contentChange={contentChange}
                    />
                </div>
            ),
        },
        {
            title: '信息验证',
            content: (
                <Form
                    {...formItemLayout}
                    initialValues={{remember: true}}
                    style={{marginTop: 80}}
                >
                    <Form.Item
                        label="管理员密码"
                        name="adminPassword"
                        rules={[{required: true, message: "请输入密码！"}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="确认密码"
                        name="confirmPassword"
                        rules={[{required: true, message: "请确认管理员密码！"}]}
                    >
                        <Input/>
                    </Form.Item>

                </Form>
            ),
        },
    ]
    const {token} = theme.useToken();
    const items = steps.map((item) => ({
        key: item.title,
        title: item.title,
    }))
    const contentStyle = {
        height: '680px',
        textAlign: 'center',
        color: token.colorTextTertiary,
        backgroundColor: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        border: `1px dashed ${token.colorBorder}`,
        marginTop: 16,
    };


    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            width: 50,
            editable: false,
            align: 'center',
            render: (_, record) => {
                return (
                    <Image width={100} src={record.cover}></Image>
                )
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
            width: 100,
            editable: false,
            align: 'center',
        },
        {
            title: '作者',
            dataIndex: 'author_name',
            width: 50,
            editable: false,
            align: 'center',
        },
        {
            title: '分类',
            dataIndex: 'sort',
            width: 50,
            editable: false,
            align: 'center',
            render: text => <span style={{color: '#1677ff'}}>{text}</span>
        },
        {
            title: '简介',
            dataIndex: 'describe',
            width: 100,
            editable: false,
            align: 'center',
            render: text => <span style={{color: '#bbb'}}>{text}</span>,
            ellipsis: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 100,
            editable: false,
            align: 'center',
            render: text => text === '草稿' ? <span style={{color: 'red'}}>{text}</span> :
                <span style={{color: '#52c41a'}}>{text}</span>
        },
        {
            title: '创建时间',
            dataIndex: 'create_time',
            width: 80,
            editable: false,
            align: 'center',
            render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
        },
        {
            title: '操作',
            width: 80,
            align: 'center',
            dataIndex: 'handle',
            render: (_, record) => {
                return (
                    <Space size="large">
                        <Tooltip title="修改">
                            <Button onClick={() => {
                                // console.log(record)
                                updateArticle(record)
                            }} type="primary">
                                <EditOutlined/>
                            </Button>
                        </Tooltip>
                        <Tooltip title="删除">
                            <Button onClick={() => {
                                setOpen(true)
                                setArticleId(record.id)
                            }} danger>
                                <DeleteFilled/>
                            </Button>
                        </Tooltip>
                    </Space>
                );
            },
        },
    ];
    const mergedColumns = columns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
            }),
        };
    });


    //批量删除按钮的功能
    const deleteChoose = () => {
        if (articleSelectedRows.length === 0) {
            setOpen(false)
        } else {
            setOpen(true)
        }
    }

    //删除方法
    const deleteOK = async () => {
        try {
            setConfirmLoading(true);
            if (articleId) {
                await reqDeleteArticleById(articleId);
            } else {
                await reqDeleteArticleList(articleSelectedRowKeys)
            }
        } catch (error) {
            message.error('删除失败');
        } finally {
            setTimeout(async () => {
                await getArticleListData();
                setOpen(false);
                setArticleId(null);
                setArticleSelectedRowKeys([]);
                message.success('删除成功');
                setConfirmLoading(false);
            }, 1000)
        }
    }

    //取消批量删除
    const deleteCancel = () => {
        setOpen(false);
    };
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            setArticleSelectedRows(selectedRows)
            setArticleSelectedRowKeys(selectedRowKeys)
        },
        onSelect: (record, selected, selectedRows) => {
            setArticleSelectedRows(selectedRows)
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
            setArticleSelectedRows(selectedRows)
        },
    };


    //分类选择器的方法
    const handleChange = async (sort) => {
        const result = await reqGetArticleList()
        setArticleListData(result.data.filter((item) => item.sort.indexOf(sort) !== -1))
    }

    //分类选择器的方法
    const handleChangeStatus = async (status) => {
        const result = await reqGetArticleList()
        setArticleListData(result.data.filter((item) => item.status.indexOf(status) !== -1))
    }

    //搜索文章
    const searchArticle = debounce(async (e) => {
        const result = await reqGetArticleList()
        setArticleListData(result.data.filter((item) => item.title.indexOf(e.target.value) !== -1))
    }, 500)

    return (
        <div>
            <Card bodyStyle={{width: '100%'}}>
                {editArticle ? null : <Space style={{width: "100%"}} size="large" direction="vertical">
                    <Space direction="horizontal"
                           style={{display: 'flex', alignItems: 'start', justifyContent: 'space-between'}}>
                        <Button type="primary" onClick={deleteChoose} danger>批量删除</Button>
                        <Form ref={searchFormRef} style={{display: 'flex'}}>
                            <Space>
                                <Form.Item name="select">
                                    <Select
                                        placeholder="筛选文章类别"
                                        style={{width: 200}}
                                        onChange={handleChange}
                                        options={sortData.map(item => ({value: item.sort, label: item.sort}))}
                                    />
                                </Form.Item>
                                <Form.Item name="selectStatus">
                                    <Select
                                        placeholder="根据状态筛选文章"
                                        style={{width: 200}}
                                        onChange={handleChangeStatus}
                                        options={[
                                            {
                                                value: '草稿',
                                                label: '草稿',
                                            },
                                            {
                                                value: '已发布',
                                                label: '已发布',
                                            }
                                        ]}
                                    />
                                </Form.Item>
                                <Form.Item name="search">
                                    <Search onChange={searchArticle} placeholder="根据标题搜索文章" enterButton/>
                                </Form.Item>
                                <Form.Item>
                                    <Button onClick={() => {
                                        searchFormRef.current.resetFields()
                                        getArticleListData()
                                    }} type="primary">重置</Button>
                                </Form.Item>

                            </Space>
                        </Form>
                    </Space>
                    <Table
                        style={{width: "100%"}}
                        bordered
                        scroll={{y: 555}}
                        rowSelection={{...rowSelection}}
                        dataSource={articleListData}
                        columns={mergedColumns}
                        rowClassName="editable-row"
                        rowKey={record => record.id}
                    />
                </Space>}
                {
                    editArticle ?
                        <div>
                            <Steps current={current} items={items}/>
                            <div style={contentStyle}>
                                {steps[current].content}
                            </div>
                            <div style={{display: 'flex', justifyContent: 'center', marginTop: 24}}>
                                {current === 0 && (
                                    <Button style={{margin: '0 8px'}} onClick={() => setEditArticle(false)}>
                                        取消
                                    </Button>
                                )}
                                {current > 0 && (
                                    <Button style={{margin: '0 8px'}} onClick={() => prev()}>
                                        上一步
                                    </Button>
                                )}
                                {current < steps.length - 1 && (
                                    <Button type="primary" onClick={() => next()}>
                                        下一步
                                    </Button>
                                )}
                                {current === steps.length - 1 && (
                                    <Button type="primary" onClick={() => updateOk()}>
                                        确认修改
                                    </Button>
                                )}
                            </div>
                        </div>
                        : null
                }
            </Card>
            {/*删除提醒框*/}
            <Modal
                centered
                title="确定要删除所选项吗？"
                open={open}
                onOk={deleteOK}
                confirmLoading={confirmLoading}
                onCancel={deleteCancel}
                okText="确认删除"
                cancelText="取消"
            >
                <p>{modalText}</p>
            </Modal>
        </div>
    );
};

export default ArticleList;